package com.jetpack_sunflower.viewmodels

import androidx.lifecycle.LiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.ViewModel
import com.jetpack_sunflower.data.GardenPlantingRepository
import com.jetpack_sunflower.data.Plant
import com.jetpack_sunflower.data.PlantRespository
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

class PlantDetailViewModel constructor(
        val plantRespository: PlantRespository,
        private val gardenPlantingRepository: GardenPlantingRepository,
        private val plantId: String
) : ViewModel() {
    val isPlanted: LiveData<Boolean>
    val plant: LiveData<Plant>

    //用来管理携程
    private val viewModelJob: Job = Job()

    //把线程的上下文提取到 viewmodeljob 中去
    private val viewModelScope = CoroutineScope(Dispatchers.Main + viewModelJob)

    init {
        val gardenPlantingForPlant = gardenPlantingRepository.getGardenPlantingForPlant(plantId)
        isPlanted = Transformations.map(gardenPlantingForPlant) {
            it != null
        }

        plant = plantRespository.getPlant(plantId)
    }

    override fun onCleared() {
        super.onCleared()
        viewModelJob.cancel()
    }

    fun addPlantToGarden() {
        viewModelScope.launch {
            gardenPlantingRepository.createGardenPalnting(plantId)
        }
    }
}